package com.fulizhe.catlocal.integration.resttemplate.config;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.data.redis.connection.RedisConfiguration.WithHostAndPort;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import com.dianping.cat.Cat;
import com.dianping.cat.message.Message;
import com.dianping.cat.message.Transaction;

import cn.hutool.core.util.ReflectUtil;

/**
 * 实现CAT对于RedisTemplate的埋点
 * 
 * @author LQ
 *
 */
@Aspect
@Component
public class RedisTemplateAspect {

	@Around("execution(* org.springframework.data.redis.core.RedisTemplate.*(..))")
	public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
		Transaction t = Cat.newTransaction("Cache", "Redis");

		RedisTemplate<?,?> rt = ((RedisTemplate<?,?>) joinPoint.getTarget());
		final WithHostAndPort hostAndPort = (WithHostAndPort) ReflectUtil.getFieldValue(rt.getConnectionFactory(),
				"configuration");

		Cat.logEvent("Cache.Source", "Source", Message.SUCCESS,
				String.format("%s:%s", hostAndPort.getHostName(), hostAndPort.getPort()));
		
		Cat.logEvent("Cache.Operate", joinPoint.getSignature().getName());
		Object returnObj = null;
		try {
			returnObj = joinPoint.proceed();
			t.setStatus(Transaction.SUCCESS);
		} catch (Exception e) {
			Cat.logError(e);
			throw e;
		} finally {
			t.complete();
		}

		return returnObj;

	}

}
